
package com.carsite.dao.hibernate;

import java.util.List;

import com.carsite.dao.hibernate.BaseDaoHibernate;
import com.carsite.model.Product;
import com.carsite.dao.ProductDao;

import org.springframework.orm.ObjectRetrievalFailureException;

public class ProductDaoHibernate extends BaseDaoHibernate implements ProductDao {

    /**
     * @see com.carsite.dao.ProductDao#getProducts(com.carsite.model.Product)
     */
    public List getProducts(final Product product) {
        return getHibernateTemplate().find("from Product");

        /* Remove the line above and uncomment this code block if you want 
           to use Hibernate's Query by Example API.
        if (product == null) {
            return getHibernateTemplate().find("from Product");
        } else {
            // filter on properties set in the product
            HibernateCallback callback = new HibernateCallback() {
                public Object doInHibernate(Session session) throws HibernateException {
                    Example ex = Example.create(product).ignoreCase().enableLike(MatchMode.ANYWHERE);
                    return session.createCriteria(Product.class).add(ex).list();
                }
            };
            return (List) getHibernateTemplate().execute(callback);
        }*/
    }

    /**
     * @see com.carsite.dao.ProductDao#getProduct(Integer id)
     */
    public Product getProduct(final Integer id) {
        Product product = (Product) getHibernateTemplate().get(Product.class, id);
        if (product == null) {
            log.warn("uh oh, product with id '" + id + "' not found...");
            throw new ObjectRetrievalFailureException(Product.class, id);
        }

        return product;
    }

    /**
     * @see com.carsite.dao.ProductDao#saveProduct(Product product)
     */    
    public void saveProduct(final Product product) {
        getHibernateTemplate().saveOrUpdate(product);
    }

    /**
     * @see com.carsite.dao.ProductDao#removeProduct(Integer id)
     */
    public void removeProduct(final Integer id) {
        getHibernateTemplate().delete(getProduct(id));
    }
}
